import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import 'logic.dart';

class WebScreenPage extends StatelessWidget {
  WebScreenPage({Key? key}) : super(key: key);

  final logic = Get.find<WebScreenLogic>();

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (b, d) {
        logic.goBack();
      },
      child: Scaffold(
        appBar: AppBar(
          title: Obx(
            () => Text(
              logic.params.value?.title ?? '',
              style: const TextStyle(color: Colors.black),
            ),
          ),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 16.w,
            ),
            onPressed: () {
              logic.goBack();
            },
          ),
        ),
        body: Obx(
          () => InAppWebView(
            onWebViewCreated: (controller) =>
                logic.setWebViewController(controller),
            initialUrlRequest:
                URLRequest(url: WebUri(logic.params.value?.url ?? '')),
            onGeolocationPermissionsShowPrompt: (controller, origin) async {
              return GeolocationPermissionShowPromptResponse(
                  allow: true, origin: origin, retain: true);
            },
            onTitleChanged: (controller, title) => logic.setTitle(title ?? ''),
            onLoadStop: (controller, url) => logic.cachedUrl = url.toString(),
            onUpdateVisitedHistory: (controller, url, androidIsReload) {
              if (url.toString() != logic.cachedUrl) {
                logic.cachedUrl = url.toString();
              }
            },
            onConsoleMessage: (controller, consoleMessage) {
              if (consoleMessage.message.contains('6. getPosition')) {
                logic.onWebLoaded();
              }
            },
            // Respond to Web page tel requests
            shouldOverrideUrlLoading: (controller, navigationAction) async {
              final uri = navigationAction.request.url;
              if (uri != null && uri.scheme == 'tel') {
                if (await canLaunchUrl(uri)) {
                  await launchUrl(uri);
                  return NavigationActionPolicy.CANCEL;
                }
              }
              return NavigationActionPolicy.ALLOW;
            },
          ),
        ),
      ),
    );
  }
}
